<template>
  <div class="container">
    <p class="title">光谷智慧交通管理平台</p>
    <div class="login-card">
      <el-card>
        <div class="menu">
          <span :class="{ sactive: activeIndex === 0 }" @click="activeIndex = 0">普通用户</span>
          <span :class="{ sactive: activeIndex === 1 }" @click="activeIndex = 1">交管部门</span>
          <span :class="{ sactive: activeIndex === 2 }" @click="activeIndex = 2">管理员</span>
        </div>
        <el-input v-model="name" @input="handleInput" style="width: 320px" placeholder="请输入用户名" />
        <el-input v-model="pwd" @input="handleInput" style="width: 320px" type="password" show-password placeholder="请输入密码" />
        <div class="pwd">
          <span class="left"><input type="checkbox" v-model="rememberMe" @change="handleRemember" />记住密码</span>
          <span class="right"><a href="">忘记密码?</a></span>
        </div>
        <div class="btns">
          <button @click="login" class="active">登录</button>
          <button @click="register" :class="{ ban: activeIndex !== 0 }">新用户注册</button>
        </div>
      </el-card>
    </div>
    <div v-if="slideIndex" class="slide">
      <Vcode @success="onSuccess" @close="onClose" :imgs="imgs" :show="true" />
    </div>
    <div v-if="registerIndex" class="register">
      <el-card>
        <p>注册账号</p>
        <p>
          <el-input v-model="registerName" style="width: 320px" placeholder="请输入用户名" />
        </p>
        <p>
          <el-input v-model="registerPwd" style="width: 320px" type="password" show-password placeholder="请输入密码" />
        </p>
        <el-button type="primary" @click="registerclose">注册</el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { h, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Vcode from 'vue3-puzzle-vcode';
import img1 from '/slideImg/img1.png';
import img2 from '/slideImg/img2.png';
import img3 from '/slideImg/img3.png';
import img4 from '/slideImg/img4.png';
import img5 from '/slideImg/img5.png';
import img6 from '/slideImg/img6.png';
import { useUserStore } from '@/stores/user';
import { storeToRefs } from 'pinia';
import * as userApi from '@/api/userRequest.js';

const imgs = [img1, img2, img3, img4, img5, img6];
const registerName = ref('');
const registerPwd = ref('');
const pwd = ref('');
const registerIndex = ref(false);
const slideIndex = ref(false);
const router = useRouter();
const { activeIndex, name } = storeToRefs(useUserStore());
const rememberMe = ref(false);
const { login: loginUser, register: registerUser } = userApi;

const login = async () => {
  const res = await loginUser({
    username: name.value,
    password: pwd.value,
    roleCode: activeIndex.value,
  });

  if (res.success) {
    // console.log(document.cookie, 'cookie');
    slideIndex.value = true;
    localStorage.setItem('userName', JSON.stringify({ username: name.value, roleCode: activeIndex.value }));
  } else {
    alert('用户名或密码错误');
  }
};

const onSuccess = () => {
  slideIndex.value = false;
  router.push({
    name: 'homeView',
  });
};

const register = async () => {
  registerIndex.value = true;
  // 清空输入框
  registerName.value = '';
  registerPwd.value = '';
};

const registerclose = async () => {
  await registerUser({
    username: registerName.value,
    password: registerPwd.value,
  })
    .then(res => {
      //提示注册成功
      registerIndex.value = false;
      alert('注册成功,请登录');
    })
    .catch(err => {
      alert(err.response.data.message);
    });
};

const onClose = () => {
  slideIndex.value = false;
};

const handleInput = () => {
  rememberMe.value = false;
};

// 记住密码功能
const handleRemember = () => {
  const users = JSON.parse(localStorage.getItem('users')) || []; // 获取现有的用户列表
  if (rememberMe.value) {
    // 如果记住密码被选中
    const existingUser = users.find(user => user.name === name.value);
    if (existingUser) {
      // 如果用户已经存在，更新密码
      existingUser.password = pwd.value;
    } else {
      // 如果用户不存在，添加新用户,从头开始添加
      users.unshift({ name: name.value, password: pwd.value });
    }
  } else {
    // 如果记住密码未被选中，删除该用户
    const index = users.findIndex(user => user.name === name.value);
    if (index !== -1) {
      users.splice(index, 1);
    }
    //清空输入框
    name.value = '';
    pwd.value = '';
  }
  // 更新 localStorage
  localStorage.setItem('users', JSON.stringify(users));
};

// 页面加载时判断是否有记住密码的用户名和密码
const init = () => {
  const users = JSON.parse(localStorage.getItem('users')) || [];
  if (users && users.length > 0) {
    //自动填充localStorage数组中储存的第一个用户信息
    const user = users[0];
    name.value = user.name;
    pwd.value = user.password;
    activeIndex.value = 0;
    rememberMe.value = true;
  }
};

// 初始化时调用 init 函数
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  background-image: url('/public/bg.gif');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  .title {
    position: absolute;
    color: white;
    font-size: 2.8em;
    top: 5%;
    left: 32%;
  }
  .login-card {
    position: absolute;
    padding: 0;
    top: 30%;
    left: 35%;
    width: 350px;
    :deep(.el-card__body) {
      padding: 30px 5px;
    }
    .menu {
      margin: 0 40px;
      margin-bottom: 10px;
      width: 80%;
      span {
        margin-right: 30px;
        text-align: center;
        font-weight: 900;
        cursor: pointer;
        padding: 2px 0;
      }
      span:hover {
        color: #0f61a1;
      }
      .sactive {
        color: #0f61a1;
        border-bottom: 2px solid #0f61a1;
      }
    }
    :deep(.el-input) {
      margin-top: 10px;
      margin-left: 5px;
    }
    .pwd {
      margin: 10px 0;
      position: relative;
      a {
        text-decoration: none;
      }
      .left {
        position: absolute;
        left: 10px;
      }
      .right {
        position: absolute;
        right: 10px;
      }
    }
    .btns {
      margin-top: 40px;
      padding: 0 10px;
      button {
        width: 100%;
        border: none;
        padding: 10px 0;
        border-radius: 5px;
        margin-top: 2px;
        background: none;
        cursor: pointer;
      }
      .active {
        background: #093866;
        color: white;
      }
      .ban {
        cursor: not-allowed;
      }
    }
  }
  .slide {
    position: absolute;
    top: 50%;
    left: 50%;
  }
  .register {
    position: absolute;
    width: 500px;
    padding: 50px 0;
    top: 30%;
    left: 30%;
    :deep(.el-card__body) {
      text-align: center;
    }
  }
}
</style>
